package com.zyx.scheduled.controller;

import cn.hutool.core.date.DateUtil;
import com.zyx.scheduled.config.DefaultSchedulingConfigurer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ScheduledFuture;

/**
 * @author Yaxi.Zhang
 * @since 2022/11/7 22:54
 */
@Slf4j
@RestController
@RequestMapping("/scheduled")
public class ScheduledController {

    @Resource
    private DefaultSchedulingConfigurer defaultSchedulingConfigurer;

    @GetMapping("/register")
    public String register(String cron) throws InterruptedException {
        log.info("task: [{}]", "register");
        while (!defaultSchedulingConfigurer.inited()) {
            Thread.sleep(200);
        }
        // URL字符转义
        // +    URL 中+号表示空格             %2B
        // 空格  URL中的空格可以用+号或者编码    %20
        // /   分隔目录和子目录                %2F
        // ?    分隔实际的URL和参数            %3F
        // %    指定特殊字符                  %25
        // #    表示书签                     %23
        // &    URL 中指定的参数间的分隔符      %26
        // =    URL 中指定参数的值            %3D
        // 0/5 * * * * ? -> 0%2F5%20*%20*%20*%20*%20%3F
        log.info("cron: [{}]", cron);
        defaultSchedulingConfigurer.addTriggerTask("task",
                new TriggerTask(
                        () -> log.info("scheduled task: [{}]", DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss")),
                        new CronTrigger(cron)));
        return "ok";
    }

    @GetMapping("/cancel")
    public String cancel() {
        log.info("task: [{}]", "cancel");
        defaultSchedulingConfigurer.cancelTriggerTask("task");
        return "ok";
    }

}
